package portal.servlet;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import java.net.URL;
import java.net.URLConnection;

import javax.servlet.*;
import javax.servlet.http.*;

import oracle.stellent.ridc.IdcClient;

import oracle.webcenter.content.stellent.StellentUtils;
import oracle.webcenter.doclib.internal.config.DocLibADFConfigUtils;

public class DocContentServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=UTF-8";
    private IdcClient idcClient;
    private String connectionName;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        try {
            connectionName = DocLibADFConfigUtils.getPrimaryConnectionName();
            idcClient = StellentUtils.getIdcClient(connectionName);


        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**Process the HTTP doGet request.
     */
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException,
                                                           IOException {
        try {
            response.setContentType(CONTENT_TYPE);
            String srurl = request.getRequestURI();
            String strpara = "";
            if (request.getQueryString() != null)
                strpara = request.getQueryString();
            //PrintWriter out = response.getWriter();
            //out.println("http://localhost:16200" + srurl);
            srurl = srurl.substring(srurl.indexOf("cs"), srurl.length());
            String connStr = idcClient.getConfig().getConnectionString();
            String ip =
                connStr.substring(connStr.indexOf("/") + 2, connStr.length());
            ip = ip.substring(0, ip.indexOf(":"));
            String filename =
                "http://" + ip + ":16200/" + srurl + "?" + strpara;

            URL u = new URL(filename);
            URLConnection uc = u.openConnection();
            //out.println(filename);
            String contentType = uc.getContentType();
            int contentLength = uc.getContentLength();            
            InputStream raw = uc.getInputStream();
            String headerFile = uc.getHeaderField("Content-Disposition");
            if(headerFile!=null)
                response.setHeader( "Content-Disposition", headerFile );            
//            if(filename.contains("/cs/idcpgl?IdcService=GETFILE")) {
//                
//            }
            response.setContentType(contentType);
            response.setContentLength(contentLength);
            response.setDateHeader("Expires",
                                   System.currentTimeMillis() + 24 * 60 * 60 *
                                   1000);
            response.setHeader("Cache-Control", "max-age=3600");
            // Get the output stream from our response object, so we
            // can write our image data to the client:
            ServletOutputStream oStream = response.getOutputStream();

            // Now, loop through buffer reads of our content, and send it to the client:
            byte[] buffer = new byte[1024];
            int len;
            while ((len = raw.read(buffer)) != -1) {
                oStream.write(buffer, 0, len);
            }

            // Now that we've sent the image data to the client, close down all the resources:
            raw.close();

            oStream.flush();
            oStream.close();
        }

        catch (IOException ioex) {
            ioex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    /**Process the HTTP doPost request.
     */
    public void doPost(HttpServletRequest request,
                       HttpServletResponse response) throws ServletException,
                                                            IOException {
        doGet(request, response);
    }

    /**Process the HTTP doPut request.
     */
    public void doPut(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException,
                                                           IOException {

    }
}
